package com.csdj.t309.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import okio.ByteString;

import java.io.IOException;
import java.util.Map;

public class HttpUtil {

    private static  OkHttpClient client = new OkHttpClient();

    private static String FILE_UPLOAD_URL = "http://localhost/upload";

    public static String get(String url){
        return get(url,null,null);
    }

    public static String get(String url,Map<String,String> params,Map<String,String> headers){

        url = url + "?" + formatParameterForForm(params);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(headers != null && headers.size() >0){
            for(Map.Entry<String,String> entry:headers.entrySet()){
                builder.header(entry.getKey(),entry.getValue());
            }
        }
        Request request = builder.build();
        try {
            final Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 下载文件并上转
     * @param url
     * @return
     */
    public static String getFileToUrl(String url, String uploadUrl){
        final Request build = new Request.Builder().url(url).build();
        try {
            final Response response = client.newCall(build).execute();
            MediaType mediaType = response.body().contentType();
            ByteString data =  response.body().byteString();
            return uploadFile(uploadUrl,data,mediaType);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String post(String url,Map<String,String> params,Map<String,String> headers){
        RequestBody requestBody = RequestBody.Companion.create(formatParameterForForm(params),MediaType.parse("application/x-www-form-urlencoded"));
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(headers != null && headers.size() >0){
            for(Map.Entry<String,String> entry:headers.entrySet()){
                builder.header(entry.getKey(),entry.getValue());
            }
        }
        builder.post(requestBody);
        Request request = builder.build();
        try {
            final Response res = client.newCall(request).execute();
            return res.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String post(String url,Map<String,String> params) {
        return post(url,params,null);
    }

    public static String post(String url, Object object){
        ObjectMapper mapper = new ObjectMapper();
        try {
            Map m = mapper.readValue(mapper.writeValueAsString(object), Map.class);
            return post(url,m);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String uploadFile(String url,ByteString data,MediaType mediaType){
        String extend = mediaType.subtype();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file",extend,RequestBody.create(data,mediaType))
                .build();
        final Request post = new Request.Builder().url(url).post(requestBody).build();
        try {
            final Response res = client.newCall(post).execute();
            return res.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String postJson(String url,String jsonData,Map<String,String> headers){
        RequestBody requestBody = RequestBody.Companion.create(jsonData,MediaType.parse("application/json"));
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(headers != null && headers.size() >0){
            for(Map.Entry<String,String> entry:headers.entrySet()){
                builder.header(entry.getKey(),entry.getValue());
            }
        }
        builder.post(requestBody);
        Request request = builder.build();
        try {
            final Response res = client.newCall(request).execute();
            return res.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *
     * @param url
     * @param json
     * @return
     */
    public static String postJson(String url,String json){
        return postJson(url,json,null);
    }


    private static String formatParameterForForm(Map<String,String> params){
        if(params != null && params.size()>0){
            StringBuilder sb = new StringBuilder();
            params.entrySet().stream().forEach(entry ->{
                sb.append(entry.getKey()+"="+entry.getValue()+"&");
            });
            return sb.substring(0,sb.length()-1);
        }
        return "";
    }

    public static void main(String[] args) {
        getFileToUrl("http://localhost/download/%E8%AF%BE%E7%A8%8B%E8%A1%A8.png",FILE_UPLOAD_URL);
    }
}
